#include "vla.h"

template<typename all>
msg copy(vla<all> from,vla<all> to)
{
    for (int i = 0; i < from.len; i++)
    {
        to.data[i]=from.data[i];
    }
    to.len=from.len;

    return success;
}

template<typename all>
long vla<all>::use_len()
{
    return this->len;
}

template<typename all>
long vla<all>::use_capacity()
{
    return this->capacity;
}

template<typename all>
all& vla<all>::operator [](int point)
{
    return this->data[point];
}

template<typename all>
msg vla<all>::push_back(all initdata)
{
    if(this->len+1>=this->capacity) // 如果数组空间不够
    {
        all *tmpPtr = new all[this->len*2]; // 重新分配空间
        memcpy(tmpPtr,this->data, sizeof(all)*this->len); // 拷贝原数组内容
        delete [] this->data;
        this->data = tmpPtr;
    }
    this->data[len+1] = initdata; //加入新的数组元素
    this->len++; 
    return success;
}

template<typename all> 
msg vla<all>::insert(all initdata,int point)
{
    if (point<0||point>this->len)
        return fail;
    else
    {
        if (this->len+1>=this->capacity) // 如果数组空间不够
        {
            all *tmpPtr = new all[this->len*2]; // 重新分配空间
            memcpy(tmpPtr,this->data, sizeof(all)*this->len); // 拷贝原数组内容
            delete [] this->data;
            this->data = tmpPtr;
        }   
        for (int i = this->len ; i > point; i--)//移动数据
        {
            this->data[i+1]=this->data[i];
        }
        this->data[point]=initdata;
        this->len++;
        return success;
    }
}

template<typename all>
msg vla<all>::erase(int point)
{
    if (point<0||point>this->len)
        return fail;
    else
    {
        for (int i = point; i < this->len; i++)
        {
            this->data[i-1]=this->data[i];
        }
        this->len--;
        return success;
    }
    
}

template<typename all>
msg vla<all>::erase(int spoint,int epoint)
{
    if(spoint<0||spoint>this->len||epoint<0||epoint>this->len)
        return fail;
    else
    {
        if (spoint>epoint)
        {
            int t;
            t=spoint;
            spoint=epoint;
            epoint=t;
        }
        
        for (int i = epoint; i < this->len; i++)
        {
            this->data[i-epoint+spoint]=this->data[i];
        }
        this->len-=(epoint-spoint);
    }
    
}

template<typename all>
msg vla<all>::fit(int size)
{
    if (size<this->len)
    {
        return fail;
    }
    all *tmpPtr = new all[size]; // 重新分配空间
    memcpy(tmpPtr,this->data, sizeof(all)*this->len); // 拷贝原数组内容
    delete [] this->data;
    this->data = tmpPtr;
    this->capacity=this->len;
    return success;
}